<template>
  <div class="page-container ">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>自动化营销</el-breadcrumb-item>
        <el-breadcrumb-item>用户组管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户分组列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!--页面内容-->
    <div class="toolbar w100">
      <el-form :model="filters" :size="size" ref="filters" :inline="true">
        <el-row class="search-input">
          <!-- <el-row class="w100">
            <el-row class="times mr30"> -->
               <el-form-item  style="margin-bottom:0 !important">
              <el-form-item label="创建时间：" prop="createTime" style="margin-right:0 !important">
                <el-date-picker
                  v-model="filters.createTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始时间"
                  class="input_postion"
                  clearable
                  @change="changeStartDate"
                  :picker-options="startDateDisabled"
                ></el-date-picker>
              </el-form-item>
              <span class="line">-</span>
              <el-form-item prop="createEndTime">
                <el-date-picker
                  v-model="filters.createEndTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束时间"
                  class="input_postion"
                  clearable
                  @change="changeEndDate"
                  :picker-options="endDateDisabled"
                ></el-date-picker>
              </el-form-item>
              </el-form-item>
            <!-- </el-row>
            <el-row class="times mr30"> --><el-form-item style="margin-bottom:0 !important">
              <el-form-item label="更新时间：" prop="updateTime" style="margin-right:0 !important">
                <el-date-picker
                  v-model="filters.updateTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始时间"
                  class="input_postion"
                  clearable
                  @change="changeUpdateStartDate"
                  :picker-options="updateStartDateDisabled"
                ></el-date-picker>
              </el-form-item>
              <span class="line">-</span>
              <el-form-item prop="updateEndTime">
                <el-date-picker
                  v-model="filters.updateEndTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束时间"
                  class="input_postion"
                  clearable
                  @change="changeUpdateEndDate"
                  :picker-options="updateEndDateDisabled"
                ></el-date-picker>
              </el-form-item></el-form-item>
            <!-- </el-row>
          </el-row> -->
          <el-form-item label="所属组织：" v-if="deptType == 0 || deptType == 1">
            <tree-select
              v-model="filters.deptId"
              :options="deptOptions"
              :clearable="false"
              :defaultExpandLevel="Infinity"
              :normalizer="normalizer"
              placeholder="请选择所属组织"
              noResultsText="暂无数据"
              :deselect="deselect()"
              style="width:178px"/>
          </el-form-item>
          <el-form-item label="用户组名称：">
            <el-input clearable
                      type="text"
                      maxlength="30"
                      v-model.trim="filters.userGroupName" placeholder="输入用户组名称"></el-input>
          </el-form-item>
          <!-- <el-row class="times"> -->
            <el-form-item label="会员数：" class="times">
              <el-input clearable type="text" maxlength="30" v-model="filters.userGroupNumber" placeholder="输入数字"
                        @input="filters.userGroupNumber=filters.userGroupNumber.replace(/[^\d.]/g,'')"></el-input>
              <span class="line">-</span>
              <el-input clearable type="text" maxlength="30" v-model="filters.maxUserGroupNumber" placeholder="输入数字"
                        @input="filters.maxUserGroupNumber=filters.maxUserGroupNumber.replace(/[^\d.]/g,'')"></el-input>
            </el-form-item>
          <!-- </el-row> -->
        </el-row>
        <el-row class="search-button">
          <el-form-item><kt-button :label="'重置'" class="resetButton" icon="el-icon-refresh" @click="resetForm"/></el-form-item>
          <el-form-item><kt-button :label="'搜索'" class="searchButton" icon="el-icon-search" @click="queryPage"/></el-form-item>
          <el-form-item><kt-button :label="'添加用户组'" class="searchButton" @click="handleAdd"/></el-form-item>
        </el-row>
      </el-form>
      <div class="tab-container">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="动态分组" name="1">
            <!-- 表格部分 -->
            <el-table :data="tableData"
                      :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                      :highlight-current-row="true"
                      :max-height="1500"
                      :size="size"
                      v-loading="loading"
                      style="width: 100%">
              <el-table-column width="100" align="center" label="ID" prop="id"></el-table-column>
              <el-table-column width="200" align="center" label="用户组名称" prop="userGroupName">
                <template slot-scope="scope">
                  {{scope.row.userGroupName == '' ? '-' : scope.row.userGroupName}}
                </template>
              </el-table-column>
              <el-table-column width="120" align="center" label="当前用户数" prop="userGroupNumber"></el-table-column>
              <el-table-column width="185" align="center" label="分组描述" prop="groupDescription">
                <template slot-scope="scope">
                  {{scope.row.groupDescription == '' ? '-' : scope.row.groupDescription}}
                </template>
              </el-table-column>
              <el-table-column width="200" align="center" label="所属组织" prop="deptName">
                <template slot-scope="scope">
                  {{scope.row.deptName == '' ? '-' : scope.row.deptName}}
                </template>
              </el-table-column>
              <el-table-column width="185" align="center" label="创建时间" prop="createTime">
                <template slot-scope="scope">
                  {{scope.row.createTime == '' ? '-' : scope.row.createTime}}
                </template>
              </el-table-column>
              <el-table-column width="185" align="center" label="更新时间" prop="updateTime">
                <template slot-scope="scope">
                  {{scope.row.updateTime == '' ? '-' : scope.row.updateTime}}
                </template>
              </el-table-column>
              <el-table-column width="500" fixed="right" label="操作" :render-header="renderHeader">
                <template slot-scope="scope">
                  <el-button type="text" @click="handlerRefreshGroup(scope.row)">刷新</el-button>
                  <el-button type="text" @click="handlerLookUserGroup(scope.row.id)">查看</el-button>
                  <el-button type="text" v-if="deptType == scope.row.deptType" @click="handleEdit(scope.row.id)">编辑
                  </el-button>
                  <el-button type="text" v-if="deptType == scope.row.deptType" @click="handleDelete(scope.row.id)">删除
                  </el-button>
                  <el-button type="text" @click="handlerLookUser(scope.row)">查看用户</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--分页栏-->
            <div class="toolbar t_r">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="currentChange"
                :current-page="pageRequest.start"
                :page-size="pageRequest.limit"
                :total="totalSize"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="sizeChange"
              ></el-pagination>
            </div>
          </el-tab-pane>

          <el-tab-pane label="静态分组" name="2">
            <!-- 表格部分 -->
            <el-table :data="tableData"
                      :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                      :highlight-current-row="true"
                      :max-height="1500"
                      :size="size"
                      v-loading="loading"
                      style="width: 100%">
              <el-table-column width="100" align="center" label="ID" prop="id"></el-table-column>
              <el-table-column width="300" align="center" label="用户组名称" prop="userGroupName">
                <template slot-scope="scope">
                  {{scope.row.userGroupName == '' ? '-' : scope.row.userGroupName}}
                </template>
              </el-table-column>
              <el-table-column width="200" align="center" label="当前用户数" prop="userGroupNumber"></el-table-column>
              <el-table-column width="185" align="center" label="分组描述" prop="groupDescription">
                <template slot-scope="scope">
                  {{scope.row.groupDescription == '' ? '-' : scope.row.groupDescription}}
                </template>
              </el-table-column>
              <el-table-column width="200" align="center" label="所属组织" prop="deptName">
                <template slot-scope="scope">
                  {{scope.row.deptName == '' ? '-' : scope.row.deptName}}
                </template>
              </el-table-column>
              <el-table-column width="200" align="center" label="创建时间" prop="createTime">
                <template slot-scope="scope">
                  {{scope.row.createTime == '' ? '-' : scope.row.createTime}}
                </template>
              </el-table-column>
              <el-table-column width="500" align="center" fixed="right" label="操作" :render-header="renderHeader">
                <template slot-scope="scope">
                  <el-button type="text" @click="handlerLookUserGroup(scope.row.id)">查看</el-button>
                  <el-button type="text" v-if="deptType != scope.row.deptId" @click="handleEdit(scope.row.id)">编辑
                  </el-button>
                  <el-button type="text" v-if="deptType != scope.row.deptId" @click="handleDelete(scope.row.id)">删除
                  </el-button>
                  <el-button type="text" @click="handlerLookUser(scope.row)">查看用户</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--分页栏-->
            <div class="toolbar t_r">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="currentChange"
                :current-page="pageRequest.start"
                :page-size="pageRequest.limit"
                :total="totalSize"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="sizeChange"
              ></el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import KtButton from '@/views/Core/KtButton'
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    components: {
      KtButton,
      TreeSelect
    },

    data() {
      return {
        size: 'mini',
        activeName: '1',
        deptType: localStorage.getItem('deptType'),             // 当前登录用户所属组织类型
        deptOptions: [],                                             // 组织集合

        // updateTime: [],
        // createTime: [],
        filters: {
          deptId: null,
          userGroupName: null,
          userGroupNumber: null,
          maxUserGroupNumber: null,
          createTime: null,
          createEndTime: null,
          updateTime: null,
          updateEndTime: null,
        },
        pageRequest: {start: 1, limit: 10},
        tableData: [],
        totalSize: 0,
        loading: false,

        startDateDisabled: {},//开始时间限制
        endDateDisabled: {},//结束时间限制

        updateStartDateDisabled: {},//开始时间限制
        updateEndDateDisabled: {},//结束时间限制
      }
    },

    mounted() {
      this.queryDeptTree()
      this.queryPage()
    },

    methods: {

      changeUpdateStartDate: function () {
        var this_ = this;
        this_.updateEndDateDisabled = {
          disabledDate: time => {
            if (this_.filters.updateTime) {
              return time.getTime() <= new Date(this_.filters.updateTime).getTime();
            }
          }
        };
      },

      changeUpdateEndDate: function () {
        var this_ = this;
        this_.updateStartDateDisabled = {
          disabledDate: time => {
            if (this_.filters.updateEndTime) {
              return time.getTime() >= new Date(this_.filters.updateEndTime).getTime();
            }
          }
        };
      },


      changeStartDate: function () {
        var this_ = this;
        this_.endDateDisabled = {
          disabledDate: time => {
            if (this_.filters.createTime) {
              return time.getTime() <= new Date(this_.filters.createTime).getTime();
            }
          }
        };
      },
      changeEndDate: function () {
        var this_ = this;
        this_.startDateDisabled = {
          disabledDate: time => {
            if (this_.filters.createEndTime) {
              return time.getTime() >= new Date(this_.filters.createEndTime).getTime();
            }
          }
        };
      },


      //所属组织 清楚选择后
      deselect() {
        if (this.filters.deptId == undefined || this.filters.deptId == null) {
          this.queryDeptTree();
        }
      },
      //所属组织初始化
      queryDeptTree() {
        let this_ = this
        this.utils.request.getAuthorDeptTree({}, res => {
          if (res.code == '0000' && res.data != null) {
            this_.deptOptions = res.data
            this_.filters.deptId = res.data[0].id
          } else {
            this_.deptOptions = []
          }
        })
      },

      //格式化组织初查询条件
      normalizer(node) {
        if (node.children == null || node.children.length == 0) {
          delete node.children
        }
        return {
          id: node.id,
          label: node.deptName,
          children: node.children
        }
      },
      queryData() {
        this.pageRequest.start = 1;
        this.queryPage();
      },
      // tabs切换
      handleClick() {
        this.pageRequest.start = 1
        this.pageRequest.limit = 10
        if (this.activeName == 1) {
          this.queryPage()
        } else {
          this.queryPage()
        }
      },

      // 用户分组查询
      queryPage() {
        // if (this.createTime.length > 0) {
        //   this.filters.createTime = this.createTime[0]
        //   this.filters.createEndTime = this.createTime[1]
        // }
        // if (this.updateTime.length > 0) {
        //   this.filters.updateTime = this.updateTime[0]
        //   this.filters.updateEndTime = this.updateTime[1]
        // }
        this.filters.start = this.pageRequest.start
        this.filters.limit = this.pageRequest.limit
        this.filters.groupType = this.activeName
        this.loading = true;
        let this_ = this
        this.utils.request.getUserGroup(this_.filters, res => {
          if (res.code == '0000' && res.data.total > 0) {
            this_.tableData = res.data.rows
            this_.totalSize = Number(res.data.total)
          } else {
            this_.tableData = []
            this_.totalSize = 0

          }
          this_.$nextTick(() => {
            this_.loading = false;
          })
        })
      },

      // 表头 操作删除提示
      renderHeader(h, {column}) {
        const inReview = '已应用的用户组不能删除'
        return h(
          'div', [
            h('span', column.label),
            h('el-tooltip', {
              effect: 'light',
              props: {
                placement: 'top'
              }
            }, [
              h('div', {
                slot: 'content',
                style: {
                  'width': '140px',
                  whiteSpace: 'normal',
                  'margin-bottom': '5px'
                }
              }, inReview),
              h('i', {
                class: 'el-icon-warning',
                style: 'color: #ffbf5e;margin-left:5px;'
              })
            ],)
          ]
        )
      },

      // 重置
      resetForm() {
        let Judgment = this.filters.createTime == null &&
          this.filters.createEndTime == null &&
          this.filters.updateTime == null &&
          this.filters.updateEndTime == null &&
          this.filters.userGroupName == null &&
          this.filters.userGroupNumber == null &&
          this.filters.maxUserGroupNumber == null &&
          this.filters.deptId == localStorage.getItem("deptId")
        if (Judgment) {
          this.$message({message: '请输入查询条件', type: 'warning'})
          return
        }
        this.filters = {
          deptId: null,
          userGroupName: null,
          userGroupNumber: null,
          maxUserGroupNumber: null,
          createTime: null,
          createEndTime: null,
          updateTime: null,
          updateEndTime: null,
        }
        // 默认所属组织为当前用户
        if (this.deptOptions != null) {
          this.filters.deptId = this.deptOptions[0].id
        }
        this.pageRequest.start = 1
        this.pageRequest.limit = 10
        this.queryPage()
      },

      // 刷新
      handlerRefreshGroup(data) {
        let refreshTime = (new Date().getTime() - new Date(data.updateTime).getTime()) / 1000
        if (refreshTime <= 60) {
          this.$message({message: '刷新后一分钟内不可重复进行刷新', type: 'warning'})
          return
        }
        let this_ = this
        this.utils.request.refreshGroup({id: data.id}, function (res) {
          if (res.code == '0000') {
            this_.$message({message: '刷新成功!', type: 'success'})
            this_.queryPage()
          } else {
            this_.$message({message: '刷新失败!', type: 'error'})
          }
        })
      },

      // 添加用户组跳转
      handleAdd() {
        let this_ = this
        this.utils.request.saveUserGroup({}, function (res) {
          if (res.code == '0000') {
            this_.$router.push('/AddUserGroup/' + res.data)
          } else {
            this_.$message({message: '请重新点击添加用户组', type: 'warning'})
          }
        })
      },

      // 查看用户组
      handlerLookUserGroup(userGroupId) {
        this.$router.push('/LookUserGroup/' + userGroupId)
      },

      // 编辑用户组跳转
      handleEdit(userGroupId) {
        let this_ = this
        this.utils.request.checkUserGroup({userGroupId: userGroupId}, function (res) {
          if (res.code == '0000') {
            if (res.data) {
              this_.openEditFail()
            } else {
              this_.$router.push('/AddUserGroup/' + userGroupId)
            }
          } else {
            this_.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
        })
      },

      // 查看用户
      handlerLookUser(data) {
        if (Number(data.userGroupNumber) <= 0) {
          this.$message({message: '当前用户数为0,请刷新后在操作', type: 'warning'})
        } else {
          this.$router.push('/LookUser/' + data.id)
        }
      },

      // 删除用户组
      handleDelete(id) {
        this.$confirm('您确定要删除该用户组？', '', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          showClose: false
        }).then(() => {
          let this_ = this
          this.utils.request.checkUserGroup({userGroupId: id}, function (res) {
            if (res.code == '0000') {
              if (res.data) {
                this_.openFail()
              } else {
                this_.utils.request.deleteUserGroup({id: id}, res => {
                  if (res.code == '0000') {
                    this_.openSuccess()
                    this_.queryPage()
                  } else {
                    this_.$message({message: '操作失败, ' + res.msg, type: 'error'})
                  }
                })
              }
            } else {
              this_.$message({message: '操作失败, ' + res.msg, type: 'error'})
            }
          })
        })
      },

      // 删除成功窗口
      openSuccess() {
        this.$alert('删除成功!', '', {
          dangerouslyUseHTMLString: true,
          showClose: false,
          closeOnClickModal: false,
          type: 'success'
        })
      },

      // 删除失败窗口
      openFail() {
        this.$confirm('该用户组正在使用,无法删除', '删除失败!', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'error',
          center: true
        })
      },

      // 编辑失败窗口
      openEditFail() {
        this.$confirm('该用户组正在使用,无法编辑', '编辑失败!', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'error',
          center: true
        })
      },

      // 分组分页方法
      currentChange(start) {
        this.pageRequest.start = start
        this.queryPage()
      },
      sizeChange(limit) {
        this.pageRequest.start = 1
        this.pageRequest.limit = limit
        this.queryPage()
      }
    }

  }
</script>

<style lang="scss" scoped>
  /deep/ .w482 {
    width: 482px !important;
  }

  //搜索表单
  .search-input {

    //当后台用俩个时间框的时候，加class:times
    .times {
      .times-to {
        padding: 0 20px;
        height: 32px;
        line-height: 32px;
        color: #999;
        display: inline-block;
      }

      /deep/ .el-input {
        width: 213px !important;

        .el-input__inner {
          width: 100% !important;
        }
      }
    }
  }

  /deep/ .el-date-editor .el-range-separator {
    color: #999;
  }


  .search-input{
    .times{
      /deep/ .el-input{
        width: 217px !important;
        .el-input__inner{
          width: 100% !important;
        }
      }
    }
  }
</style>
